package com.ruoyi.web.controller.example;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.resturant.domain.ResShop;
import com.ruoyi.resturant.service.IResShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Anonymous
@RestController
@RequestMapping("/api/redis")
@Api(tags = "Redis测试")
public class RedisController {
    @Autowired
    private IResShopService resShopService;
    @Autowired
    private RedisCache redisCache;
    //往Redis插入数据

    /**
     * 根据店铺ID查询店铺详情，并把店铺信息存入Redis中
     * @param id 店铺ID
     * @return
     */
    @ApiOperation("根据店铺ID查询店铺详情，并把店铺信息存入Redis中")
    @ApiImplicitParam(name = "id", value = "店铺ID",
            required = true, dataType = "long", paramType = "path",
            dataTypeClass = Long.class)
    @GetMapping("/{id}")
    public AjaxResult setRedisObj(@PathVariable("id") Long id) {
        ResShop resShop = resShopService.selectResShopById(id);

        String str = JSON.toJSONString(resShop);

        redisCache.setCacheObject(String.valueOf(id), str, 1, TimeUnit.HOURS);

        return AjaxResult.success(resShop);
    }

    /**
     * 根据店铺ID从Redis取店铺的详情
     * @param id
     * @return
     */
    @ApiOperation("根据店铺ID查询从redis中查询店铺详情")
    @ApiImplicitParam(name = "id", value = "店铺ID",
            required = true, dataType = "long", paramType = "path",
            dataTypeClass = Long.class)
    @GetMapping("/ids/{id}")
    public AjaxResult getRedisObj(@PathVariable("id") Long id) {
        // 1 根据店铺ID从redis取得店铺详情的json字符串
        String str = redisCache.getCacheObject(String.valueOf(id));
        // 2 把店铺详情的json字符串转换为一个model对象ResShop
        ResShop resShop = JSON.parseObject(str, ResShop.class);
        // 3 返回取得model对象
        return AjaxResult.success(resShop);
    }

}
